from google.appengine.ext import db
from nerd.modules import User_formulas, Notebooks, NotebooksConst
from nerd.modules import UserConstants
from nerd.compute.constants import GetConstSplit 



class Library(object):
    
    def __init__(self, user = None,notebook = None):
        self.user = user
        self.notebook = notebook
    
    def get_all(self):
        userFormulas = db.GqlQuery("SELECT * FROM User_formulas WHERE user = :1", self.user)
        return userFormulas
    
    def get_formulas(self):
        userFormulas = db.GqlQuery("SELECT * FROM User_formulas WHERE user = :1 and formula = :2", self.user, True)
        return userFormulas
    
    def get_conste(self):
        userFormulas = db.GqlQuery("SELECT * FROM UserConstants WHERE user = :1", self.user)
        return userFormulas
    
    def get_notebook(self):
        notebooks_prop = db.GqlQuery("SELECT * FROM Notebooks WHERE nbID = :1", self.notebook)
        notebook_formulas = [(x.date ,x.formulaID) for x in notebooks_prop]
        notebooks_prop = db.GqlQuery("SELECT * FROM NotebooksConst WHERE nbID = :1", self.notebook)       
        notebook_const = [(x.date ,x.formulaID) for x in notebooks_prop]
        notebook = notebook_const + notebook_formulas
        notebook.sort()
        notebook = [obj for date, obj in notebook] #@UnusedVariable
        return notebook
    
    def get_notebooks(self):
        #notebooks_formulas = Notebooks.gql("WHERE user = :1", self.user)
        #notebooks_constants = NotebooksConst.gql("WHERE user = :1", self.user)
        notebooks_formulas = Notebooks.all()
        notebooks_constants = NotebooksConst.all()
        return set(x.nbID 
                   for nbs in (notebooks_formulas, notebooks_constants) 
                       for x in nbs)
    
    def get(self, kind, key):
        if kind == 'formula':
            return User_formulas.get(key)
        else:
            return UserConstants.get(key)
    
    def put(self, kind, data_object, expression):
        if kind == 'formula':
            data_object.content = expression
        else:
            const_split = GetConstSplit(expression)
            data_object.name, data_object.content = const_split
    
    def delete(self, kind, data_object):
        notebooks = {'formula': Notebooks, 
                     'constant': NotebooksConst}[kind]
        for f in notebooks.gql("WHERE formulaID = :1", data_object):
            f.delete()
    
    def update(self, kind, key, expression):
        chngd = self.get(kind, key)
        if chngd is not None:
            if expression:
                self.put(kind, chngd, expression)
                chngd.put()
                return chngd
            else:
                self.delete(kind, chngd)
                chngd.delete()
        